; ((doc) => {
  let imgs = doc.querySelector('.imgBox')
  let prev = doc.querySelector('#prev')
  let next = doc.querySelector('#next')
  let circles = doc.querySelectorAll('.circle li')

  const init = () => {
    prev.addEventListener('click', handlePrevImg, false)
    next.addEventListener('click', handleNextImg, false)
  }
  let first = imgs.children[0].cloneNode(true)
  imgs.appendChild(first)

  let index = 0
  let time

  // 节流锁
  let lock = true

  /**
   * 图片移动 正序
   */
  const nextPosition = () => {
    imgs.style.transition = '.7s ease-out'
    if (index === 4) {
      setTimeout(() => {
        imgs.style.left = 0
        imgs.style.transition = 'none'
        index = 0
      }, 700)
    }
    imgs.style.left = (index * -100) + '%'
  }
  /**
   * 图片移动 逆序
   */
  const prevPosition = () => {
    if (index < 1) {
      imgs.style.transition = 'none'
      imgs.style.left = (4 * -100) + '%'
      setTimeout(() => {
        imgs.style.transition = '.7s ease-out'
        imgs.style.left = (3 * -100) + '%'
      }, 0)
      index = 3
    } else {
      index--
      imgs.style.left = (index * -100) + '%'
    }
  }

  const timer = () => {
    time = setInterval(() => {
      index++
      console.log('我自动触发了 index:', index);
      nextPosition()
      handlehover()
    },3500)
  }
 
  const handlePrevImg = () => {
    if (!lock) return
    prevPosition()
    console.log(`我是上一张图 index:${index}`);
    clearInterval(time)
    timer()
    handlehover()
    lock = false
    setTimeout(() => {
      lock = true
    }, 700);
  }
  
  const handleNextImg = () => {
    if (!lock) return
    index++
    console.log(`我是下一张图 index:${index}`);
    nextPosition()
    handlehover()
    clearInterval(time)
    timer()
    lock = false
    setTimeout(() => {
      lock = true
    }, 700);
  }

  const handlehover = () => {
    for (let j = 0; j < circles.length; j++) {
      circles[j].id = ''
    }
    if (index === 4) {
      circles[0].id = 'hover'
    } else {
      circles[index].id = 'hover'
    }
  }

  for (let i = 0; i < circles.length; i++) {
    circles[i].addEventListener('click', () => {
      index = i
      console.log(`我是小圆点 index:${index}`);
      nextPosition()
      clearInterval(time)
      handlehover()
      timer()
    }, false)
  }

  timer()
  init()
})(document)